#include "logAnalyzer.h"

LogAnalyzer::LogAnalyzer(int argc, char *argv[]) : m_argc(argc)
{
    for(int i = 0; i < m_argc; i++) {
	m_argv.push_back(argv[i]);
    }

    m_db = new Database(m_argv);
    m_dbIsInit = true;
    cout << "SUCCESS" << endl;
	    
    for(size_t i = 0; i < m_argv.size(); i++) {
	if(m_argv[i] == "-f") {
	    openFile(m_argv[i+1]);
	    i = m_argv.size()+1;
	} else if(m_argv[i] == "--help") {
	    cout << "Usage :\n"
		"--help : Show help\n"
		"-f /path/to/file : File to analyze\n"
		"--server foo : IP or URL of the SQL server\n"
		"--user bar : name of the user for login to mysql\n"
		"--password lala : password for login to mysql\n"
		"--database fun : set the database to use\n"
		"--create-tables : create tables for statistics\n"
		"If tables aren't created, they will be created automatically\n";
	    m_dbIsInit = false;
	}
    }
}

LogAnalyzer::~LogAnalyzer() {
    if(m_dbIsInit)
	delete m_db;
}

void LogAnalyzer::openFile(const string filePath) {
    m_file = new ifstream(filePath.c_str(), ios::in);

    if(*m_file) {
	loop();
	m_file->close();
    } else {
	cerr << "Cannot open file !" << endl;
    }
    delete m_file;
}

void LogAnalyzer::loop() {
    string line;
    while(getline(*m_file, line)) {
	analyzeLine(line);
    }
}

/*
  This function analyze the line and call the adapted function
*/
void LogAnalyzer::analyzeLine(const string line) {
    if(stringStartWith(line.substr(7), "InitGame:"))
	m_gameId = newGame(line.substr(7));
}

bool LogAnalyzer::stringStartWith(const string line, const string start) {
    if(line.substr(0, start.size()) == start)
	return true;
    else 
	return false;
}

/*
  This function add a new game in the database
*/
int LogAnalyzer::newGame(const string str) {
    string mapName = findValueOf(str, "mapname");
    string gameType = findValueOf(str, "gametype");
    m_db->newGameQuery(mapName, gameType);
    return 0;
}

/*
  Search the value of an option in the string
*/
string LogAnalyzer::findValueOf(const string str, const string option) {
    size_t begin = str.find(option, 0) + option.size() + 1;
    size_t length = str.substr(begin).find('\\');
    return str.substr(begin, length);
}

